<?php
/**
 * Created by PhpStorm.
 * User: ZhangWei
 * Date: 2018/2/5
 * Time: 17:58
 */

namespace App\Http\Controllers\Api\Mp;


use App\Http\Controllers\Api\ApiBase;
use App\Http\Resources\CategorieCollection;
use App\Models\Categorie;
use App\Models\Doc;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class DocController extends ApiBase
{

    public function my_doc()
    {
        $user = $this->getUser();
        $doc = Doc::query()->where('user_id', $user->id);
    }

    public function add_before()
    {
        $user = $this->getUser();
        $data['categorie'] = new CategorieCollection(Categorie::query()->whereNull('parent_id')->orderByDesc('order')->get());
        return $this->success($data);

    }


    public function submit_data(Request $request)
    {
        $user = $this->getUser();
        $req = $request->all();
        $validator = Validator::make($req, [
            'id' => 'filled',
            'name' => ['required', Rule::unique('users')->ignore($user->id)],
            'abstract' => 'required|between:5,32',
            'cover' => 'required',
            'cover_id' => 'required',
            'category_id' => 'required|array',
        ], [
            'name.required' => '请输入标题',
            'name.unique' => '标题已存在',
            'abstract.required' => '请输入简介',
            'cover.required' => '请上传封面',
            'category_id.required' => '请选择分类',
        ]);
        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }
        $data = [
            'name' => $req['name'],
            'abstract' => $request['abstract'],
            'category_data' => $request['category_id'],
            'category_id' => $request['category_id'][count($request['category_id']) - 1],
            'content' => $request['content'],
            'user_id' => $user->id,
            'cover' => $req['cover'],
            'cover_id' => $req['cover_id']
        ];
        if (!empty($req['id'])) {
            $doc = Doc::ckId($req['id'], $user->id);
            if ($doc == false) {
                return $this->failed('数据错误');
            }
            $doc->save($data);
        } else {
            $doc = Doc::query()->create($data);
        }

        return $this->success(Doc::getHashId($doc));

    }

}